﻿using System.Collections.Concurrent;

namespace PmSoft.Core.Reflection
{
	/// <summary>
	/// 反射上下文缓存
	/// </summary>
	internal static class ReflectionContextCache
	{
		private static readonly ConcurrentDictionary<Type, WeakReference<ReflectionContext>> _cache = new();

		/// <summary>
		/// 获取或添加反射上下文
		/// </summary>
		/// <param name="type">类型</param>
		/// <returns>反射上下文</returns>
		public static ReflectionContext GetOrAdd(Type type)
		{
			if (_cache.TryGetValue(type, out var weakRef) && weakRef.TryGetTarget(out var context))
				return context;

			context = new ReflectionContext(type);
			_cache.TryAdd(type, new WeakReference<ReflectionContext>(context));
			return context;
		}
	}
}

